package com.zjdiepu.www.biz.base;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.qiniu.processing.OperationStatus;
import com.qiniu.processing.OperationStatus.OperationResult;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.MediaProcessStatus;
import com.zjdiepu.www.base.enums.type.AttachmentLabel;
import com.zjdiepu.www.base.enums.type.AttachmentSort;
import com.zjdiepu.www.base.enums.type.AttachmentType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.ZhppDateUtil;
import com.zjdiepu.www.config.FileProperty;
import com.zjdiepu.www.dao.base.OtherAttachmentsMapper;
import com.zjdiepu.www.dao.other.OtherMediaFailMapper;
import com.zjdiepu.www.dao.zpp.PublicDao;
import com.zjdiepu.www.dao.zx.ZxQueryCreditApplySubMapper;
import com.zjdiepu.www.ibiz.base.IOtherAttachmentsService;
import com.zjdiepu.www.ibiz.file.IQiniuFileService;
import com.zjdiepu.www.model.base.dto.OtherAttachments;
import com.zjdiepu.www.model.base.ext.OtherAttachmentsExt;
import com.zjdiepu.www.model.other.dto.OtherMediaFail;
import com.zjdiepu.www.model.zx.dto.ZxQueryCreditApplySub;
import com.zjdiepu.www.model.zx.ext.ZxQueryCreditApplySubExt;

/**
 * 附件信息Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月03日 11时48分<br/>
 * @since 1.0<br/>
 */
@Service
public class OtherAttachmentsServiceImpl extends BaseService implements IOtherAttachmentsService {
	public static final Logger logger = LoggerFactory.getLogger(OtherAttachmentsServiceImpl.class);

	@Autowired
	private ZxQueryCreditApplySubMapper zxQueryCreditApplySubMapper;
	@Autowired
	private IQiniuFileService qiniuFileService;
	@Autowired
	private OtherAttachmentsMapper otherAttachmentsMapper;
	@Autowired
	private OtherMediaFailMapper otherMediaFailMapper;
	@Resource
	private FileProperty fileProperty;
	
	@Resource
	private PublicDao publicDao;
	@Override
	public void deleteInvalidAttachments(String applyId, AbstractSysUser sysUser) {
		if(StringUtils.isBlank(applyId)) {
			return;
		}
		//清除不依附子申请ID的附件
		ZxQueryCreditApplySubExt zxQueryCreditApplySubExt = new ZxQueryCreditApplySubExt();
		zxQueryCreditApplySubExt.setQueryCreditApplyId(applyId);
		zxQueryCreditApplySubExt.setBaseWhere();
		List<ZxQueryCreditApplySub> zxQueryCreditApplySubs = zxQueryCreditApplySubMapper.selectByExt(zxQueryCreditApplySubExt);
		if(CollectionUtils.isNotEmpty(zxQueryCreditApplySubs)) {
			List<String> applySubIds = zxQueryCreditApplySubs.stream().map(item -> item.getId()).collect(Collectors.toList());
			applySubIds.add(applyId);//兼容老数据(使用了主申请的ID)
			OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
			otherAttachmentsExt.setBaseWhere();
			otherAttachmentsExt.withOutPage();
			otherAttachmentsExt.setAttachmentType(AttachmentType.IMAGE.getCode());
			otherAttachmentsExt.setDataid(applyId);
			otherAttachmentsExt.setExcludeSubDataids(applySubIds);
			List<OtherAttachments> otherAttachments = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
			for(OtherAttachments otherAttachment : otherAttachments) {
				otherAttachment.initDeleteData(sysUser.getId(), sysUser.getName());
				otherAttachment.setRemarks("清除不依附子申请ID的附件");
				otherAttachmentsMapper.deleteByPrimaryKey(otherAttachment.getId());
			}
		}
	}
	
	@Override
	public String uploadWord(AbstractSysUser sysUser, String wordFileName, ModeIDType wordModeId, AttachmentSort wordAttachmentSort,  AttachmentLabel wordAttachmentLabel, String wordBusid,/*word参数*/
			String applyId, String subApplyId, List<String> includeFileLabels, List<String> excludeFileLabels /*图片参数*/) {
		
		OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
		otherAttachmentsExt.withOutPage();
		otherAttachmentsExt.setBaseWhere();
		otherAttachmentsExt.setIncludeFileLabels(includeFileLabels);
		otherAttachmentsExt.setExcludeFileLabels(excludeFileLabels);
		otherAttachmentsExt.setDataid(applyId);
		otherAttachmentsExt.setSubDataid(subApplyId);
		List<OtherAttachments> otherAttachments = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
		
		otherAttachmentsExt.setDataid(wordBusid);
		otherAttachmentsExt.setSubDataid(null);
		otherAttachments.addAll(otherAttachmentsMapper.selectByExt(otherAttachmentsExt));
		if(CollectionUtils.isEmpty(otherAttachments)) {
			return null;
		}
		List<String> fileNames  = otherAttachments.stream().filter(item -> StringUtils.isNotBlank(item.getFileName())).map(item -> item.getFileName()).collect(Collectors.toList());
		if(CollectionUtils.isEmpty(fileNames)) {
			return null;
		}
		String uploadZx = qiniuFileService.uploadZx(true, wordFileName, fileNames.toArray(new String[fileNames.size()]));
		
		//添加附件
		OtherAttachments otherAttachments_ = new OtherAttachments();
		otherAttachments_.setDpStatus(DpStatus.NORMAL.getCode());
		otherAttachments_.setDataid(wordBusid);
		otherAttachments_.setAttachmentSort(wordAttachmentSort.getCode());
		otherAttachments_.setFileLabel(wordAttachmentLabel.getCode());
		otherAttachments_ = otherAttachmentsMapper.selectRefined(otherAttachments_);
		boolean insert = false;
		if(null == otherAttachments_) {
			otherAttachments_ = new OtherAttachments();
			otherAttachments_.initInsertData(sysUser.getId(), sysUser.getName());
			insert = true;
		} else {
			otherAttachments_.initUpdateData(sysUser.getId(), sysUser.getName());
		}
		otherAttachments_.setDataid(wordBusid);
		otherAttachments_.setModeId(wordModeId.getCode());
		otherAttachments_.setAttachmentSort(wordAttachmentSort.getCode());
		otherAttachments_.setFileLabel(wordAttachmentLabel.getCode());
		otherAttachments_.setAttachmentType(AttachmentType.WORD.getCode());
		otherAttachments_.setCustomLabelName(wordAttachmentLabel.getValue());
		otherAttachments_.setFileName(uploadZx);
		otherAttachments_.setOssPath(uploadZx);
		otherAttachments_.setFileShowName(uploadZx);
		if(insert) {
			otherAttachmentsMapper.insert(otherAttachments_);
		} else {
			otherAttachmentsMapper.updateByPrimaryKeySelective(otherAttachments_);
		}
		return wordFileName;
	}
	
	@Override
	public void saveProcessedMediaFile(OtherMediaFail otherMediaFail){
		Integer dataStatus = otherMediaFail.getDataStatus();
		if(MediaProcessStatus.CHENG_GONG.getCode().equals(dataStatus)) {
			updateAttachements(otherMediaFail);
		} else if(!MediaProcessStatus.CHU_LI_SHI_BAI.getCode().equals(dataStatus)) { //处理已经确认失败的
			String persistentId = otherMediaFail.getPersistentId();
			OperationStatus operationStatus = qiniuFileService.queryStatusByPersistentId(persistentId);
			if(null == operationStatus){
				//TODO:获取状态失败，需要根据日记判断错误，并修正
				return;
			}
			if(operationStatus.code == MediaProcessStatus.CHENG_GONG.getCode() || operationStatus.code == MediaProcessStatus.TONG_ZHI_TI_JIAO_SHI_BAI.getCode()) {
				OperationResult[] items = operationStatus.items;
				if(ArrayUtils.isEmpty(items)) {
					return;
				}
				OperationResult noticeResult = items[0];
				String newFileName = noticeResult.key;
				otherMediaFail.setKeyFile(newFileName);
			}
			otherMediaFail.setDataStatus(operationStatus.code);
			updateAttachements(otherMediaFail);
		} else {
			//TODO:处理失败的，不更新附件信息。可以检查后,再处理
			otherMediaFail.setNum((otherMediaFail.getNum() == null ? 0 : otherMediaFail.getNum()) + 1);
			otherMediaFailMapper.updateByPrimaryKeySelective(otherMediaFail);
		}
	}
	
	private void updateAttachements(OtherMediaFail otherMediaFail){
		Integer dataStatus = otherMediaFail.getDataStatus();
		if(MediaProcessStatus.CHENG_GONG.getCode().equals(dataStatus) || MediaProcessStatus.TONG_ZHI_TI_JIAO_SHI_BAI.getCode().equals(dataStatus) ) {
			String idAttachments = otherMediaFail.getIdAttachments();
			String typeFile = otherMediaFail.getTypeFile();
			if(StringUtils.isNotBlank(idAttachments)){
				if(AttachmentType.RAR.getCode().equals(typeFile)) { //rar需要维护osspath filename
					OtherAttachments otherAttachments = new OtherAttachments();
					otherAttachments.setId(idAttachments);
					otherAttachments.setFileName(otherMediaFail.getKeyFile());
					otherAttachments.setOssPath(otherMediaFail.getKeyFile());
					otherAttachmentsMapper.updateByPrimaryKeySelective(otherAttachments);
				}
			}
			otherMediaFailMapper.deleteByPrimaryKey(otherMediaFail.getId());
		} else {
			otherMediaFailMapper.updateByPrimaryKeySelective(otherMediaFail);
		}
	}
	
	@Override
	public String saveWordToQiniu(String zxcxApplyId,String zxsubId, AttachmentSort attachmentSort, AbstractSysUser sysUser, String... urls) {
		//征信人类别
		String credit_people_type = "";
		//征信人类别
		
		String wordOsspth = "";
		
		AttachmentSort currentAttachmentSort = null;
		switch (attachmentSort) {
		case SHEN_FEN_ZHENG_MING:
			currentAttachmentSort = AttachmentSort.ZHENG_XIN_SHOU_QUAN_WORD;
			credit_people_type = "03";
			break;
		case PEI_OU_SHEN_FEN_ZHENG_MING:
			currentAttachmentSort = AttachmentSort.PEI_OU_ZHENG_XIN_SHOU_QUAN_WORD;
			credit_people_type = "01";
			break;
		case DAN_BAO_REN_SHEN_FEN_ZHENG_MING_1:
			currentAttachmentSort = AttachmentSort.DAN_BAO_REN_ZHENG_XIN_SHOU_QUAN_WORD_1;
			credit_people_type = "02";
			break;
		case DAN_BAO_REN_SHEN_FEN_ZHENG_MING_2:
			currentAttachmentSort = AttachmentSort.DAN_BAO_REN_ZHENG_XIN_SHOU_QUAN_WORD_2;
			credit_people_type = "02";
			break;
		case DAN_BAO_REN_SHEN_FEN_ZHENG_MING_3:
			currentAttachmentSort = AttachmentSort.DAN_BAO_REN_ZHENG_XIN_SHOU_QUAN_WORD_3;
			credit_people_type = "02";
			break;
		case DAN_BAO_REN_SHEN_FEN_ZHENG_MING_4:
			currentAttachmentSort = AttachmentSort.DAN_BAO_REN_ZHENG_XIN_SHOU_QUAN_WORD_4;
			credit_people_type = "02";
			break;
		default:
			break;
		}
		if(null == currentAttachmentSort) { //其他类型不生成word
			return wordOsspth;
		}
		
		//附件名称
		String fileName = "";
		//附件名称
		
		//征信字表主键
		String subDataId = "";
		//征信字表主键
		String creditPeopleType = "";
		String sqlXmls = "";
		if(StringUtils.isNotBlank(zxsubId))
		{
			sqlXmls = "select t.id,t.cus_name,t.cus_no,t.credit_people_type from zx_query_credit_apply_sub t where t.query_credit_apply_id = '"+zxcxApplyId+"' and t.credit_people_type = '"+credit_people_type+"' and t.id = '"+zxsubId+"' and t.dp_status = 1 limit 1";
		}
		else
		{
			sqlXmls = "select t.id,t.cus_name,t.cus_no,t.credit_people_type from zx_query_credit_apply_sub t where t.query_credit_apply_id = '"+zxcxApplyId+"' and t.credit_people_type = '"+credit_people_type+"' and t.dp_status = 1 limit 1";
		}
		List<Map<String, String>> list = publicDao.queryWhereSql(sqlXmls);
		if(null != list && 0 != list.size())
		{
			for(int i=0;i<list.size();i++)
			{
				Map<String, String> maps = list.get(i);
				
				creditPeopleType = maps.get("credit_people_type").toString();
				subDataId = maps.get("id").toString();
				
				if(creditPeopleType.equals("03"))
				{
					creditPeopleType = "主借人"; 
//					@update 2018-02-08
//					subDataId = zxcxApplyId; 
				}
				else if(creditPeopleType.equals("01"))
				{
					creditPeopleType = "配偶";
				}
				else if(creditPeopleType.equals("02"))
				{
					creditPeopleType = "担保人";
				}
				
				String cus_name = maps.get("cus_name").toString();
				String cus_no = maps.get("cus_no");
				
//				if(null == cus_no || cus_no.length() < 18)
				if(StringUtils.isBlank(cus_no))
				{
					throw new BaseException("100900","身份证格式错误！");
				}
				
				cus_no = cus_no.substring(14);
				fileName = ZhppDateUtil.DateToString(new Date(),"yyyyMMddHHmmss")+"_"+cus_name+"_"+cus_no+".doc";
			}
		}
		
		if(null == fileName || ("").equals(fileName))
		{
			//throw new BaseException(ResultFlagType.FAIL.getCode().toString(),"fileName is null  || Please check carefully to confirm the accuracy of the data");
			return "";
		}
		
		//查询附件表信息
		boolean isKey = false;
		if(ArrayUtils.isEmpty(urls) && StringUtils.isNotBlank(zxcxApplyId)) 
		{
			OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
			otherAttachmentsExt.setBaseWhere();
			otherAttachmentsExt.withOutPage();
			otherAttachmentsExt.setDataid(zxcxApplyId);
			otherAttachmentsExt.setSubDataid(subDataId);
			otherAttachmentsExt.setModeId(ModeIDType.ZXCX.getCode());
			List<OtherAttachments> otherAttachments = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
			if("03".equals(credit_people_type) && CollectionUtils.isEmpty(otherAttachments)) { //主借人附件为空时，需要兼容sub表不匹配attachment sub_dataid
				otherAttachmentsExt.setSubDataid(zxcxApplyId);
				otherAttachments = otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
			}
			Set<String> urls_ = otherAttachments.stream().map(item -> item.getOssPath()).collect(Collectors.toSet());
			isKey = true;
			urls = urls_.toArray(new String[urls_.size()]);
		}
		
		if(null == urls || 0 == urls.length)
		{
			return "";
		}
		
		wordOsspth = qiniuFileService.uploadZx(isKey,fileName, urls);
		
		//添加附件
		OtherAttachments otherAttachments_ = new OtherAttachments();
		if(null == sysUser)
		{
			otherAttachments_.initInsertData("00000000000000000000000000000000", "超级管理员");
		}
		else
		{
			otherAttachments_.initInsertData(sysUser.getId(), sysUser.getName());
		}
		otherAttachments_.setModeId(ModeIDType.ZXCX.getCode());
		otherAttachments_.setDataid(zxcxApplyId);
		otherAttachments_.setSubDataid(subDataId);
		otherAttachments_.setAttachmentSort(currentAttachmentSort.getCode());
		otherAttachments_.setAttachmentType(AttachmentType.WORD.getCode());
		otherAttachments_.setFileLabel(AttachmentLabel.SHOU_QUAN_ZHENG_MING.getCode());
		otherAttachments_.setCustomLabelName(AttachmentLabel.SHOU_QUAN_ZHENG_MING.getValue());
		otherAttachments_.setFileShowName(wordOsspth);
		otherAttachments_.setFileName(wordOsspth);
		otherAttachments_.setOssPath(wordOsspth);
		otherAttachmentsMapper.insert(otherAttachments_);
		return wordOsspth;
	}
	
	@Override
	public void update(OtherAttachments otherAttachments) {
		// 影响的记录数
		otherAttachmentsMapper.updateByPrimaryKeySelective(otherAttachments);
	}
	
	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly = false)
	public void updateJust(OtherAttachments otherAttachments) {
		// 影响的记录数
		otherAttachmentsMapper.updateByPrimaryKeySelective(otherAttachments);
	}
	
	@Override
	public void insert(OtherAttachments otherAttachments) {
		otherAttachmentsMapper.insert(otherAttachments);
	}
	
	@Override
	@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly = false)
	public void insertJust(OtherAttachments otherAttachments) {
		otherAttachmentsMapper.insert(otherAttachments);
	}
	
	@Override
	public void saveUpdateAndDelete(OtherAttachments otherAttachments, OperateType operType,String upDelete) {
		switch (operType) {
		case add:
			otherAttachments.initInsertData(otherAttachments.getModifier(), otherAttachments.getModifierName());
			if("1".equals(upDelete)){
				otherAttachments.setDpStatus(0);
			}
			otherAttachmentsMapper.insert(otherAttachments);
			break;
		case edit:
			otherAttachments.initUpdateData(otherAttachments.getModifier(), otherAttachments.getModifierName());
			// 影响的记录数
			int updateCount = otherAttachmentsMapper.updateByPrimaryKeySelective(otherAttachments);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			otherAttachments.initDeleteData(otherAttachments.getModifier(), otherAttachments.getModifierName());
			// 影响的记录数
			int deleteCount = otherAttachmentsMapper.updateByPrimaryKeySelective(otherAttachments);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<OtherAttachments> selectByExt(OtherAttachmentsExt otherAttachmentsExt) {
		return otherAttachmentsMapper.selectByExt(otherAttachmentsExt);
	}
	
	@Override
	public int countByExt(OtherAttachmentsExt otherAttachmentsExt){
		return otherAttachmentsMapper.countByExt(otherAttachmentsExt);
	}
	
	@Override
	public OtherAttachments selectById(String id) {
		return otherAttachmentsMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			otherAttachmentsMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(OtherAttachments otherAttachments) {
		return otherAttachmentsMapper.countRefined(otherAttachments);
	}

	@Override
	public OtherAttachments selectRefined(OtherAttachments otherAttachments) {
		return otherAttachmentsMapper.selectRefined(otherAttachments);
	}
	
	@Override
	public int deletedRefined(OtherAttachments otherAttachments) {
		return otherAttachmentsMapper.deletedRefined(otherAttachments);
	}

	@Override
	public boolean repeat(OtherAttachments otherAttachments) {
		int count = countRefined(otherAttachments);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(otherAttachments.getId())) {
			return true;
		}
		OtherAttachments dbItem = selectRefined(otherAttachments);
		if(null == dbItem) {
			return false;
		}
		return !otherAttachments.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return otherAttachmentsMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<OtherAttachments> otherAttachmentss) {
		return otherAttachmentsMapper.insertBatch(otherAttachmentss);
	}
}
